<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Influencer;
use App\Models\Report;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use App\Http\Requests\ReportRequest;

class ReportController extends Controller
{
    /**
     * 创建举报
     */
    public function store(ReportRequest $request): JsonResponse
    {
        $validated = $request->validated();
        // 先写死平台id
        $validated['platform_id'] = 1;
        $validated['severity_level'] = 'low';

        try {
            DB::beginTransaction();

            // 查找或创建网红
            $influencer = Influencer::firstOrCreate(
                [
                    'platform_id' => $validated['platform_id'],
                    'platform_user_id' => $validated['platform_user_id'],
                ],
                [
                    'name' => '未知用户', // 这里可以通过平台API获取用户信息
                    'score' => 5.0,
                ]
            );

            // 创建举报记录
            $report = Report::create([
                'user_id' => $request->user()->id,
                'influencer_id' => $influencer->id,
                'type' => $validated['type'],
                'content' => $validated['content'],
                'evidence' => $validated['evidence'],
                'severity_level' => $validated['severity_level'],
            ]);

            // 更新网红评分和举报次数
            $influencer->increment('report_count');
            $this->updateInfluencerScore($influencer);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '举报成功',
                'data' => $report
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '举报失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新网红评分
     */
    private function updateInfluencerScore(Influencer $influencer): void
    {
        $reports = $influencer->reports()
            ->where('created_at', '>=', now()->subMonths(3))
            ->get();

        if ($reports->isEmpty()) {
            return;
        }

        $totalScore = 0;
        $weightSum = 0;

        foreach ($reports as $report) {
            $weight = match ($report->severity_level) {
                'low' => 1,
                'medium' => 2,
                'high' => 3,
                'critical' => 4,
                default => 1,
            };

            $totalScore += $weight;
            $weightSum += $weight;
        }

        $newScore = max(0, min(10, 10 - ($totalScore / $weightSum) * 5));
        $influencer->update(['score' => $newScore]);
    }

    /**
     * 获取举报列表
     */
    public function index(Request $request): JsonResponse
    {
        
        // 校验查询参数，platform_user_id 为必填，其余参数可选
        try {
            $validated = $request->validate([
                'platform_user_id' => ['required', 'string'],
                'severity_level'   => ['nullable', Rule::in(['low', 'medium', 'high', 'critical'])],
                'type'             => ['nullable', 'string'],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败：' . $e->getMessage()
            ], 422);
        }
        
        // // 平台暂时写死为 1
        $platformId      = 1;
        $platformUserId  = $validated['platform_user_id'];

        $query = Report::query()
            ->with(['influencer', 'user:id,name'])
            ->whereHas('influencer', function ($q) use ($platformId, $platformUserId) {
                $q->where('platform_id', $platformId)
                  ->where('platform_user_id', $platformUserId);
            })
            ->when($validated['severity_level'] ?? null, function ($query, $severityLevel) {
                $query->where('severity_level', $severityLevel);
            })
            ->when($validated['type'] ?? null, function ($query, $type) {
                $query->where('type', $type);
            })
            ->latest();

        $reports = $query->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $reports
        ]);
    }

    /**
     * 根据平台用户 ID 获取举报次数
     */
    public function count(Request $request): JsonResponse
    {
        // 校验查询参数
        try {
            $validated = $request->validate([
                'platform_user_id' => ['required', 'string'],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败：' . $e->getMessage(),
            ], 422);
        }

        // 平台暂时写死为 1
        $platformId     = 1;
        $platformUserId = $validated['platform_user_id'];

        $influencer = Influencer::where('platform_id', $platformId)
            ->where('platform_user_id', $platformUserId)
            ->first();

        $reportCount = $influencer?->report_count ?? 0;

        return response()->json([
            'success' => true,
            'data'    => [
                'report_count' => $reportCount,
            ],
        ]);
    }
} 